import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Table, Button, Badge, Modal, List, Card } from 'antd';
import styles from './SimCard.less';
import SearchForm from '../../components/SearchForm/index';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { getSimExportUrl } from '../../services/api';

@connect(({ simcard }) => ({
  simcard,
}))
export default class SimCardList extends PureComponent {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: '日期',
        dataIndex: 'monDate',
        key: 'monDate',
      },
      {
        title: '时段',
        dataIndex: 'timeSlot',
        key: 'timeSlot',
      },
      {
        title: 'SIM卡号',
        dataIndex: 'iccid',
        key: 'iccid',
        render: text => (
          <a onClick={() => this.props.history.push(`/dashboard/simcarddetail/${text}`)}>{text}</a>
        ),
      },
      {
        title: '设备ID',
        dataIndex: 'devId',
        key: 'devId',
      },
      {
        title: 'SIM卡流量(MB)',
        dataIndex: 'simFlow',
        key: 'simFlow',
        render: text => text && (Number.parseInt(text) / (1024 * 1024)).toFixed(2),
      },
      {
        title: '主通道流量(MB)',
        dataIndex: 'flow',
        key: 'flow',
        render: text => text && (Number.parseInt(text) / (1024 * 1024)).toFixed(2),
      },
      {
        title: 'RTS通道流量(MB)',
        dataIndex: 'rtsFlow',
        key: 'rtsFlow',
        render: text => text && (Number.parseInt(text) / (1024 * 1024)).toFixed(2),
      },
      {
        title: '在线状态',
        key: 'online',
        dataIndex: 'online',
        render: text => (
          <div>
            <Badge status={text ? 'processing' : 'default'} />
            {text ? '在线' : '离线'}
          </div>
        ),
      },
      {
        title: 'SIM卡状态',
        key: 'status',
        dataIndex: 'status',
        render: status => (
          <div>
            <Badge status={status ? 'success' : 'default'} />
            {status ? '已激活' : '已停用'}
          </div>
        ),
      },
      {
        title: '时间',
        dataIndex: 'createTime',
        key: 'createTime',
      },
    ];
    this.state = {
      formValues: {}
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'simcard/fetchSimCardList',
      payload: {
        current: 1,
        pageSize: 10,
        iccid: '',
        devId: '',
        startTime: '',
        endTime: '',
        online: '',
        status: '',
      }
    });
  }

  onChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
    };
    dispatch({
      type: 'simcard/fetchSimCardList',
      payload: params
    });
  };

  handleSearch = (params) => {
    const { dispatch, simcard: { pagination } } = this.props;
    this.setState({ formValues: params });
    dispatch({
      type: 'simcard/fetchSimCardList',
      payload: { page: 1, pageSize: pagination.pageSize, ...params },
    });
  };

  handleModalClose = () => {
    this.setState(this.defaultState);
    const { dispatch } = this.props;
    dispatch({
      type: 'simcard/resetFilteredList',
    });
  };

  handleListLoadMore = () => {
    const { dispatch } = this.props;
    const current = this.state.listPage + 1;
    this.setState({
      listPage: current,
    });
    dispatch({
      type: 'simcard/fetchSimCardList',
      payload: {
        ...this.state,
        current,
      },
    });
  };
  onExport = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'simcard/onExport',
      payload: { ...this.state.formValues },
      callback: src => {
        const link = document.createElement('a');
        link.download = 'filename';
        link.style.display = 'none';
        link.href = src;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      },
    });
  }
  render() {
    const { pagination, total, isLoading, hasMore } = this.props.simcard;
    const { showModal, iccid, devId, startTime, endTime, online, status } = this.state;
    return (
      <PageHeaderLayout>
        <Card>
          <Fragment>
            <div className={styles.headRow}>
              <SearchForm onSearch={this.handleSearch} />
              <div className={styles.headRight}>
                <Button >
                  <a href={getSimExportUrl(this.state.formValues)}>
                    导出
                  </a>
                </Button>
                <Button
                  onClick={() => {
                    window.location.reload();
                  }}
                >
                  刷新
                </Button>
              </div>
            </div>
            <Table
              columns={this.columns}
              dataSource={this.props.simcard.list}
              // pagination={{
              //   current: pagination.current,
              //   pageSize: this.state.pageSize,
              //   total: total,
              //   showQuickJumper: true,
              //   showSizeChanger: true,
              //   pageSizeOptions: ['10', '20', '50', '100'],
              // }}
              onChange={this.onChange}
              loading={isLoading}
            />
            <Modal
              onCancel={this.handleModalClose}
              visible={showModal}
              width={800}
              footer={
                [] // 设置footer为空，去掉 取消 确定默认按钮
              }
            >
              <List
                itemLayout="horizontal"
                dataSource={this.props.simcard.filteredList}
                loading={isLoading}
                loadMore={
                  hasMore && (
                    <div
                      style={{
                        textAlign: 'center',
                        marginTop: 12,
                        height: 32,
                        lineHeight: '32px',
                      }}
                    >
                      <Button onClick={this.handleListLoadMore}>加载更多</Button>
                    </div>
                  )
                }
                style={{ height: '800px', overflow: 'scroll' }}
                header={
                  <div className={styles.listRow}>
                    <div className={styles.iccid}>ICCID</div>
                    <div className={styles.devId}>设备ID</div>
                    <div className={styles.usage}>周期累计用量(MB)</div>
                    <div className={styles.online}>在线状态</div>
                    <div className={styles.status}>SIM卡状态</div>
                  </div>
                }
                renderItem={item => (
                  <div className={styles.listRow}>
                    <div className={styles.iccid}>
                      <a
                        onClick={() =>
                          this.props.history.push(`/dashboard/simcarddetail/${item.iccid}`)
                        }
                      >
                        {item.iccid}
                      </a>
                    </div>
                    <div className={styles.devId}>{item.devId}</div>
                    <div className={styles.usage}>
                      {item.ctdDataUsage &&
                        (Number.parseInt(item.ctdDataUsage) / (1024 * 1024)).toFixed(2)}
                    </div>
                    <div className={styles.online}>
                      <Badge status={item.online ? 'processing' : 'default'} />
                      {item.online ? '在线' : '离线'}
                    </div>
                    <div className={styles.status}>
                      <Badge status={item.status === 'ACTIVATED' ? 'success' : 'default'} />
                      {item.status === 'ACTIVATED' ? '已激活' : '已停用'}
                    </div>
                  </div>
                )}
              />
            </Modal>
          </Fragment>
        </Card>
      </PageHeaderLayout>
    );
  }
}
